package tgc.edu.yzy.custom;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.forte.qqrobot.BaseConfiguration;

/***
 * HTTP 傻仙接口专用机器人接口
 * @author 936642284
 *
 */
public class HttpSx {
	public static String getImage(String requestUrl,String type) {
		String resout = "";
		long startTime1 = System.currentTimeMillis(); 
		HttpURLConnection conn = null;
        BufferedReader br = null;
        int responseCode = 0;
        try {
        	String Url = "https://yzycoc.oss-cn-shanghai.aliyuncs.com/" + requestUrl;
            URL url = new URL(Url);
            conn = (HttpURLConnection) url.openConnection();
            //设置请求方式
            conn.setRequestMethod("GET");
            //设置请求内核
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.81 Safari/537.36");
            conn.setRequestProperty("Referer","936642284");
            //设置使用缓存
            conn.setUseCaches(false);
            //设置链接超时时间,毫秒为单位
            conn.setConnectTimeout(60000);
            //设置读取超时时间，毫秒为单位
            conn.setReadTimeout(60000);
            //设置当前链接是否自动处理重定向。setFollowRedirects设置所有的链接是否自动处理重定向
            //conn.setInstanceFollowRedirects(false);
            //开启链接
            conn.connect();
            //获取反馈的情况200
             responseCode = conn.getResponseCode();
            if(responseCode == 200) {
            	//获取反馈回来的数据类型
            	String contentType = conn.getContentType();
            	if("image/png".equals(contentType)){
            		InputStream inStream = conn.getInputStream();
            		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            		byte[] date = new byte[1024];
            		int is = 0;
            		while((is = inStream.read(date)) != -1){
            			outStream.write(date,0,is);
    	            }
            		String fileurl= "C:\\cocutil\\"+type+"\\"+requestUrl;
            		File file = new File(fileurl);
            		FileOutputStream op = new FileOutputStream(file);
            		op.write(outStream.toByteArray());
            		op.close();
            		return null;
            	}else {
            		resout = "未知反馈，请截图反馈作者"+contentType;
            		return resout;
            	}
            }
            resout = "查询失败，接口正在维护！";
            return resout;
        } catch (Exception e) {
        	e.printStackTrace();
        	resout = "查询超时，无法获取图片！";
            return resout;
        }finally{
        	long endTime=System.currentTimeMillis();
        	System.out.println(responseCode+": OOS下载图片用时： "+(endTime-startTime1)+"ms");
            //关闭流和链接
            if(null != br){
                try {
					br.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
            }
            if(null != conn){
                conn.disconnect();
            }
        }
	}
	
	public static String[] getURL(String requestUrl,Map<String,Object> data,String method){
		String resout[] = {"0",""};
		long startTime1 = System.currentTimeMillis(); 
		HttpURLConnection conn = null;
        BufferedReader br = null;
        StringBuffer sb = new StringBuffer();
        //GET请求的url链接
        int responseCode = 0;
        if(null == method || "GET" == method){
            requestUrl = requestUrl+"?"+urlEncode(data);
        }
        try {
            URL url = new URL(requestUrl);
            conn = (HttpURLConnection) url.openConnection();
            System.out.println(requestUrl);
            //设置请求方式
            if("GET" == method || null == method){
                conn.setRequestMethod("GET");
            }else{
                conn.setRequestMethod("POST");
                //使用URL连接输出
                conn.setDoOutput(true);
            }
            //设置请求内核
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.81 Safari/537.36");
            conn.setRequestProperty("Cookie","_ga=GA1.2.1599053079.1569457387; _gid=GA1.2.2047943731.1569457387");
            //设置使用缓存
            conn.setUseCaches(false);
            //设置链接超时时间,毫秒为单位
            conn.setConnectTimeout(60000);
            //设置读取超时时间，毫秒为单位
            conn.setReadTimeout(60000);
            //设置当前链接是否自动处理重定向。setFollowRedirects设置所有的链接是否自动处理重定向
            //conn.setInstanceFollowRedirects(false);
            //开启链接
            conn.connect();
            //获取反馈的情况200
            responseCode = conn.getResponseCode();
            if(responseCode == 200) {
            	//获取反馈回来的数据类型
            	String contentType = conn.getContentType();
            	if("application/json; charset=utf-8".equals(contentType)) {
            		//处理post请求时的参数
    	            if(null != data && "POST" == method){
    	                DataOutputStream out = new DataOutputStream(conn.getOutputStream());
    	                out.writeBytes(urlEncode(data));
    	            }
    	            //获取字符输入流
    	            br = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
    	            String strContent = null;
    	            while((strContent = br.readLine()) != null){
    	                sb.append(strContent);
    	            }
    	            String content = sb.toString();
    	            JSONObject j = JSON.parseObject(content);
    	            resout[0] = j.getString("ok");
    	            resout[1] = j.getString("msg");
    	            return resout;
            	}else {
            		resout[1] = "未知反馈，请截图反馈作者"+contentType;
            		return resout;
            	}
            }
            resout[1] = "查询失败，接口正在维护！";
            return resout;
        } catch (Exception e) {
        	resout[1] = "查询超时，无法获取图片！";
            return resout;
        }finally{
        	long endTime=System.currentTimeMillis();
        	System.out.println(responseCode+"傻仙接口调用时间： "+(endTime-startTime1)+"ms  "+data.get("info"));
            //关闭流和链接
            if(null != br){
                try {
					br.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
            }
            if(null != conn){
                conn.disconnect();
            }
        }
	}
	 //将map型转为请求参数型
  public static String urlEncode(Map<String, ?> data) {
      if(data == null){
          return "";
      }else{
          StringBuilder sb = new StringBuilder();
          for (Map.Entry<String, ?> i : data.entrySet()) {
              try {
                  sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue() + "", "UTF-8")).append("&");
              } catch (UnsupportedEncodingException e) {
                  e.printStackTrace();
              }
          }
          return sb.toString();
      }
  }
}
